package com.library.controller;

import com.library.dto.LoginDTO;
import com.library.entity.User;
import com.library.service.UserService;
import com.library.util.JwtUtil;
import com.library.vo.LoginVO;
import com.library.vo.ResultVO;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResultVO<LoginVO> login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());

            User user = userService.getByUsername(loginDTO.getUsername());

            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);
            loginVO.setTokenType("Bearer");
            loginVO.setUserId(user.getId());
            loginVO.setUsername(user.getUsername());
            loginVO.setRealName(user.getRealName());
            loginVO.setRole(user.getRole());

            log.info("用户登录成功 - {}", loginDTO.getUsername());
            return ResultVO.success("登录成功", loginVO);
        } catch (Exception e) {
            log.error("用户登录失败 - {}, 错误: {}", loginDTO.getUsername(), e.getMessage());
            return ResultVO.error(e.getMessage());
        }
    }

    @GetMapping("/me")
    public ResultVO<User> getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            User user = userService.getByUsername(username);
            if (user != null) {
                user.setPassword(null);
            }

            return ResultVO.success(user);
        } catch (Exception e) {
            log.error("获取当前用户信息失败: {}", e.getMessage());
            return ResultVO.error("获取用户信息失败");
        }
    }
}
